package com.anysoft.user;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.adapter.OnItemClickListener;
import com.anysoft.adapter.UserManageAdapter;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.LoginOutBean;
import com.anysoft.bean.UserBean;
import com.anysoft.login.LoginActivity;
import com.anysoft.login.UserIconLoginActivity;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.view.ItemRemoveRecyclerView;
import com.anysoft.view.dialog.DialogUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wwq on 2017/1/20.
 * 用户切换列表,可滑动删除条目
 * 废弃
 */

public class UserManageActivity extends BaseActivity {

    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.rv_user_manage)
    ItemRemoveRecyclerView mRecyclerView;

    private LinearLayoutManager mLayoutManager;
    private ArrayList<UserBean> userBeanList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_user_manage);
        ButterKnife.bind(this);

        title.setText("用户切换");

        userBeanList.addAll(findUserList());

        //创建默认的线性LayoutManager
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        mRecyclerView.setHasFixedSize(true);

        initViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initViews() {
        final UserManageAdapter adapter = new UserManageAdapter(this, userBeanList);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                if (position == userBeanList.size()) {
                    startActivity(new Intent().setClass(mActivity, LoginActivity.class));
                    finish();
                } else {
                    UserBean userBean = userBeanList.get(position);
                    if (mentorApplication.userBean != null && mentorApplication.userBean.getUserId().equals(userBean.getUserId())) {
                        showToast("该账户已登录");
                        return;
                    }
//                    showToast("-----" + userBeanList.get(position).getUserId() + "-----");

                    if (mentorApplication.userBean != null) {
                        DialogUtils utils = new DialogUtils();
                        utils.contentAlert(mActivity, "提示", "确定要退出当前账户", "确定", "取消");
                        utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                            @Override
                            public void OnContentDialogSbtnClick() {
                                loginOut(userBeanList.get(position));
                            }
                        });
                    } else {
                        Intent intent = new Intent().setClass(mActivity, UserIconLoginActivity.class);
                        intent.putExtra("userId", userBeanList.get(position).getUserId());
                        startActivity(intent);
                        finish();
                    }
                }
            }

            @Override
            public void onDeleteClick(final int position) {
                final UserBean userBean = userBeanList.get(position);
                if (mentorApplication.userBean != null && mentorApplication.userBean.getUserId().equals(userBean.getUserId())) {
                    showToast("当前登录账户不能删除");
                    return;
                }

                DialogUtils utils = new DialogUtils();
                utils.contentAlert(mActivity, "是否删除账户", "删除当前账户，将清除账户在手机上所有资料信息。", "删除", "取消");
                utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                    @Override
                    public void OnContentDialogSbtnClick() {
                        if (deleteUser(userBean.getUserId())) {
                            clearSecretKey(mActivity);
                            adapter.removeItem(position);
                        }
                    }
                });
            }
        });
    }

    public void loginOut(final UserBean userBean) {
        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());

        OkGo.<String>post(HostConstant.LOGIN_OUT)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateLoginOut(response.body(),userBean);
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateLoginOut(String json, UserBean userBean) {

        LoginOutBean bean;

        try {
            bean = new Gson().fromJson(json, LoginOutBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        mentorApplication.signOut();
        AnalyticsEventUtils.toLogoutEvent(this);
        Intent intent = new Intent().setClass(mActivity, UserIconLoginActivity.class);
        intent.putExtra("userId", userBean.getUserId());
        //System.out.println("userBeanList.get(position).getUserId()---" +
//                userBean.getUserId());
        startActivity(intent);
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @OnClick({R.id.leftButton, R.id.rightButton})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                finish();
                break;
            case R.id.rightButton:
                break;
        }
    }
}
